// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-11-19

#include "stdafx.h"
#include "svr_netmsg.h"
#include "net_transmit.h"
#include <common/netmsg/aes.h>

namespace JoyServer
{
namespace JoyMsgTool
{

using namespace JoyMessage;

static BYTE s_aesKey[] =
{
    0x71, 0x89, 0x91, 0x97, 0x75, 0xAB, 0xD4, 0xC2,
    0xA1, 0x79, 0xD1, 0x47, 0x35, 0x79, 0x5C, 0xD6,
    0xB3, 0xB9, 0x31, 0x56, 0x77, 0xCC, 0x8E, 0xE9,
    0xC9, 0xE9, 0x11, 0xD3, 0x59, 0xEF, 0x9F, 0x3A,
};
static CJoyAes s_msgCrypto(s_aesKey, sizeof(s_aesKey));

JoyMessage::MessageBase* ExtractMsg(const void* buf, int len)
{
    if(len < sizeof(JoyMessage::MessageBase))
    {
        return NULL;
    }

    JoyMessage::MessageBase* msg = (JoyMessage::MessageBase*)buf;

    if((UINT)len < msg->m_size)
    {
        return NULL;
    }

    if(msg->m_crypto)
    {
        int nCryptoSize = len-sizeof(JoyMessage::MessageHeader);
        if((nCryptoSize&0x0000000F) != 0)
        {
            return NULL;
        }
        BYTE* pCryptoBuf = (BYTE*)buf+sizeof(JoyMessage::MessageHeader);
        s_msgCrypto.Decrypt(pCryptoBuf, pCryptoBuf, nCryptoSize);
    }

    return msg;
}

CJoyTransmitData* BuildMsgData(const JoyMessage::MessageBase* msg)
{
    CJoyTransmitData* pMsgData;
    if(msg->m_crypto)
    {
        UINT nCryptoSize = (msg->m_size-sizeof(MessageHeader)+15)&0xFFFFFFF0;
        UINT nSockMsgSize= nCryptoSize+sizeof(MessageHeader);
        
        pMsgData = new CJoyTransmitData(nSockMsgSize+sizeof(int));
        BYTE* pMsgBuf = (BYTE*)pMsgData->m_buf.GetBuffer();
        *(int*)pMsgBuf = nSockMsgSize;
        pMsgBuf += sizeof(int);
        memcpy(pMsgBuf, msg, msg->m_size);
        memset(pMsgBuf+msg->m_size, 0, nSockMsgSize-msg->m_size);
        BYTE* pCryptoBuf = pMsgBuf+sizeof(MessageHeader);
        s_msgCrypto.Encrypt(pCryptoBuf, pCryptoBuf, nCryptoSize);
    }
    else
    {
        pMsgData = new CJoyTransmitData(msg->m_size+sizeof(int));
        BYTE* pMsgBuf = (BYTE*)pMsgData->m_buf.GetBuffer();
        *(int*)pMsgBuf = msg->m_size;
        pMsgBuf += sizeof(int);
        memcpy(pMsgBuf, msg, msg->m_size);
    }
    return pMsgData;
}

} // namespace JoyMsgTool

} // namespace JoyServer